package com.pzr.soccer.email;

import com.pzr.soccer.aop.metric.MetricTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
@Slf4j
public class MailService {
	@Autowired
	JavaMailSender javaMailSender;

	@Async
	@MetricTime("sendEmail")
	public void sendEmail(ToEmail toEmail) {
		
		//创建简单邮件消息
	    SimpleMailMessage message = new SimpleMailMessage();
	    //谁发的
	    message.setFrom("714534524@qq.com");
	    //谁要接收
	    message.setTo(toEmail.getTo());
	    //邮件标题
	    message.setSubject(toEmail.getSubject());
	    //邮件内容
	    message.setText(toEmail.getContent());
	    try {
			System.out.println("sending email..."+toEmail.getSubject());
			javaMailSender.send(message);
	      System.out.println("send email successfully!");
	    } catch (MailException e) {
	      e.printStackTrace();
	      log.error("send email fail !");
	    }

	}

	@Async
	@MetricTime("sendHtmlEmail")
	public void sendHtmlEmail(ToEmail toEmail) {
		MimeMessage message=javaMailSender.createMimeMessage();

		try {
			MimeMessageHelper  helper = new MimeMessageHelper(message,true);

			//谁发的
			helper.setFrom("714534524@qq.com");
			//谁要接收
			helper.setTo(toEmail.getTo());
			//邮件标题
			helper.setSubject(toEmail.getSubject());
			//邮件内容
			helper.setText(toEmail.getContent(),true);
			System.out.println("sending email..."+toEmail.getSubject());
			javaMailSender.send(message);
			System.out.println("send email successfully!");
		} catch (MailException | MessagingException e) {
			e.printStackTrace();
			log.error("send email fail !");
		}

	}
}
